<template>
  <div class="form-box">
    <el-form 
      ref="ruleFormRef" 
      :model="form" 
      :rules="rules"
      label-width="150px">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>利用者情報</span>
          </div>
        </template>
        <el-descriptions>
          <el-descriptions-item label="漢字氏名：">{{ kjname }}</el-descriptions-item>
          <el-descriptions-item label="カナ氏名：">{{ knname }}</el-descriptions-item>
          <el-descriptions-item label="出生年月日：">{{ btday }}</el-descriptions-item>
          <el-descriptions-item label="性別：">{{ seibetu }}</el-descriptions-item>
          <el-descriptions-item label="婚姻状況：">{{ marryStatus }}</el-descriptions-item>
          <el-descriptions-item label="会社：">{{ kaisya }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>自宅情報</span>
          </div>
        </template>
        <el-row>
          <el-form-item label="自宅漢字住所" prop="address1">
            <el-input v-model="form.address1" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="自宅電話番号" prop="phonenum">
            <el-input v-model="form.phonenum" style="width: 200px"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="自宅カナ住所" prop="address2">
            <el-input v-model="form.address2" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="自宅郵便番号" prop="passcode">
            <el-input v-model="form.passcode" style="width: 200px"></el-input>
          </el-form-item>
        </el-row>
      </el-card>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>勤務先情報</span>
          </div>
        </template>
        <el-row>
          <el-form-item label="勤務先漢字住所" prop="companyAddress1">
            <el-input v-model="form.companyAddress1" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="勤務先電話番号" prop="companyPhonenum">
            <el-input v-model="form.companyPhonenum"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="勤務先カナ住所" prop="companyAddress2">
            <el-input v-model="form.companyAddress2" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="勤務先郵便番号" prop="companyPasscode">
            <el-input v-model="form.companyPasscode"></el-input>
          </el-form-item>
        </el-row>
      </el-card>
      <div class="button-container">
        <el-button type="primary" @click="submitForm">登録</el-button>
        <el-button @click="resetForm">リセット</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { searchUserDetails as fetchUserDetails, updateDetail } from '@/apis/user';
import { ElMessage } from 'element-plus';

const form = ref({
  address1: '',
  phonenum: '',
  address2: '',
  passcode: '',
  companyAddress1: '',
  companyPhonenum: '',
  companyAddress2: '',
  companyPasscode: '',
});

// 漢字氏名
const kjname = ref('');
// カナ氏名
const knname = ref('');
// 生年月日
const btday = ref('');
// 性別
const seibetu = ref('');
// 婚姻状況
const marryStatus = ref('');
// 会社名称
const kaisya = ref('');

const validatePhone = (rule, value, callback) => {
  if (!/^\d+$/.test(value)) {
    return callback(new Error('電話番号は数字で入力ください'));
  }
  if (value.length < 10 || value.length > 13) {
    return callback(new Error('電話番号は10桁以上、13桁以下で入力ください'));
  }
  if (!/^[\u0020-\u007E]*$/.test(value)) {
    return callback(new Error('電話番号は半角文字で入力ください'));
  }
  return callback();
};

const validatePasscode = (rule, value, callback) => {
  if (!/^\d+$/.test(value)) {
    return callback(new Error('郵便番号は数字で入力ください'));
  }
  if (!/^[\u0020-\u007E]*$/.test(value)) {
    return callback(new Error('郵便番号は半角文字で入力ください'));
  }
  return callback();
};

const validateFullWidth = (rule, value, callback) => {
  if (!/^[^\u0020-\u007E]*$/.test(value)) {
    return callback(new Error('漢字住所は全角文字で入力ください'));
  }
  return callback();
};

const validateHalfWidth = (rule, value, callback) => {
  if (!/^[\u0020-\u007E\uFF61-\uFF9F]*$/.test(value)) {
    return callback(new Error('住所は半角文字で入力ください'));
  }
  return callback();
};

const rules = reactive({
  address1: [
    { validator: validateFullWidth, trigger: 'blur' },
  ],
  address2: [
    { validator: validateHalfWidth, trigger: 'blur' },
    { required: true, message: 'カナ住所を入力ください', trigger: 'blur' },
  ],
  phonenum: [
    { validator: validatePhone, trigger: 'blur' },
  ],
  companyAddress1: [
    { validator: validateFullWidth, trigger: 'blur' },
  ],
  companyAddress2: [
    { validator: validateHalfWidth, trigger: 'blur' },
    { required: true, message: 'カナ住所を入力ください', trigger: 'blur' },
  ],
  companyPhonenum: [
    { validator: validatePhone, trigger: 'blur' },
  ],
  passcode: [
    { validator: validatePasscode, trigger: 'blur' },
  ],
  companyPasscode: [
    { validator: validatePasscode, trigger: 'blur' },
  ],
});

const ruleFormRef = ref(null);

const submitForm = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      console.log('submit!');
      updateDetail(form.value).then((res) => {
        if (res.data.code === 200) {
          ElMessage.success('変更しました！');
        } else {
          ElMessage.error('変更できません。');
        }
      }).catch((error) => {
        ElMessage.error('変更中にエラーが発生しました。');
        console.error('変更エラー:', error);
      });
    } else {
      console.log('error submit!', fields);
    }
  });
};

const resetForm = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.resetFields();
};

onMounted(() => {
  fetchUserDetails().then((res) => {
    console.log('User data:', res);
    const data = res.data.data;
    kjname.value = data.kanjiname;
    knname.value = data.kananame;
    btday.value = `${data.birthday.substring(0, 4)}/${data.birthday.substring(4, 6)}/${data.birthday.substring(6, 8)}`;
    seibetu.value = data.sex === 0 ? '男' : '女';
    marryStatus.value = data.married === 0 ? '未婚' : '既婚';
    kaisya.value = data.company;
    form.value = {
      address1: data.address1,
      phonenum: data.phonenum,
      address2: data.address2,
      passcode: data.passcode,
      companyAddress1: data.companyAddress1,
      companyAddress2: data.companyAddress2,
      companyPhonenum: data.companyPhonenum,
      companyPasscode: data.companyPasscode,
    };
  }).catch((error) => {
    ElMessage.error('ユーザー情報を取得中にエラーが発生しました。');
    console.error('请求失败', error);
  });
});
</script>

<style lang="scss" scoped>
.el-descriptions {
  margin-top: 20px;
}

.box-card {
  margin-bottom: 10px;
  > div {
    > div {
      text-align: left;
    }
  }
}

.button-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
